import { _decorator, assert, Color, color, Component, instantiate, Label, Node, Prefab, ProgressBar, Sprite, SpriteFrame } from 'cc';
import { Core } from '../Core/Core';
import { EState, EEvent, EPlayerType,ESkill, EBaseAttribute, EPath, EGameMode, EView } from '../Config/Enum';
import { PlayerManager } from '../PlayerManager';
import { EPassiveSkill, SkillConfig } from '../Config/SkillConfig';
import { PlayerConfig } from '../Config/PlayerConfig';

import { PlayerData } from '../PlayerData';
import { Util } from '../Util';
import { ResourceManager } from '../Core/ResourceManager';
import { PicPath, PrefabPath } from '../Config/ResourceConfig';
import { EEquipmentType, ItemQualityColors } from '../Item/Item';
import { BagItem } from '../Item/BagItem';
const { ccclass, property } = _decorator;

@ccclass('PlayerView')
export class PlayerView extends Component {
    ndBG

    player
    playerPrefab
    playerType
    playerData: PlayerData
    playerName: Label
    // currentPlayer: EPlayerType
    ndSkills: Node
    playerList: EPlayerType[] = [EPlayerType.Shaolin, EPlayerType.Tangmen, EPlayerType.Emei, EPlayerType.Gaibang, EPlayerType.Wudang]
    lbWuxing: Label
    ndPlayerList: Node
    ndAttributes: Node
    ndSecondAttributes: Node
    ndEquipmentSwitchView: Node
    ndPlayerInfo: Node

    currIndex: number = 1
    // 属性
    lbStrength: Label
    lbAgility: Label
    lbIntelligence: Label
    lbInnerPower: Label
    lbVitality: Label
    primaryAttribute: EBaseAttribute
    lbRage: Label

    lbCriticalChance: Label
    lbCriticalDamage: Label
    lbAP: Label
    lbDP: Label
    lbAttackSpeed: Label
    lbAttackRange: Label
    lbHP: Label
    lbWuxingEnhance: Label
    lbSkillEnhance: Label
    lbIgnoreDefense: Label
    lbAccuracy: Label
    lbCDR:Label
    lbDodge:Label

    baseAttackSpeed: number
    // 装备
    ndHelmet: Node
    ndArmor: Node
    ndWeapon: Node
    ndLeggings: Node
    ndShoes: Node
    ndPendant: Node
    ndBelt: Node
    ndBracers: Node

    ndEquipment: Node
    ndEXP: Node
    ndLevel: Node

    // 武学
    ndPassiveSkill1: Node
    ndPassiveSkill2: Node

    


        // 装备节点
    private equipmentNodes: Map<EEquipmentType, Node> = new Map();


    protected onLoad(): void {
        console.log("onload PlayerView");

        //父节点
        this.ndAttributes = this.node.getChildByName('Attributes')
        this.ndSecondAttributes = this.ndAttributes.getChildByName('ScrollView').getChildByName('view').getChildByName('content')
        this.ndEquipmentSwitchView = this.node.parent.getChildByName('EquipmentSwitchView')
        this.ndPlayerInfo = this.node.getChildByName('PlayerInfo')
    
        // 玩家数据
        this.player = this.ndPlayerInfo.getChildByName('PlayerBG').getChildByName('Player')
        this.playerName = this.ndPlayerInfo.getChildByName('PlayerName').getChildByName("Label").getComponent(Label)
        this.ndLevel = this.ndPlayerInfo.getChildByName('Level')
        this.lbWuxing = this.ndPlayerInfo.getChildByName('Wuxing').getComponent(Label)
        this.ndPlayerList = this.node.getChildByName('PlayerList')
        this.ndEXP = this.ndPlayerInfo.getChildByName('EXP')

        // 属性
        this.lbStrength = this.ndAttributes.getChildByName('Label_Strength').getChildByName('Value').getComponent(Label);
        this.lbAgility = this.ndAttributes.getChildByName('Label_Agility').getChildByName('Value').getComponent(Label)
        this.lbIntelligence = this.ndAttributes.getChildByName('Label_Intelligence').getChildByName('Value').getComponent(Label)
        this.lbInnerPower = this.ndAttributes.getChildByName('Label_InnerPower').getChildByName('Value').getComponent(Label)
        this.lbVitality = this.ndAttributes.getChildByName('Label_Vitality').getChildByName('Value').getComponent(Label)
        this.lbCriticalChance = this.ndSecondAttributes.getChildByName('Label_CriticalChance').getChildByName('Value').getComponent(Label)
        this.lbCriticalDamage = this.ndSecondAttributes.getChildByName('Label_CriticalDamage').getChildByName('Value').getComponent(Label)
        this.lbAP = this.ndSecondAttributes.getChildByName('Label_AP').getChildByName('Value').getComponent(Label)
        this.lbDP = this.ndSecondAttributes.getChildByName('Label_DP').getChildByName('Value').getComponent(Label)
        this.lbAttackSpeed = this.ndSecondAttributes.getChildByName('Label_AttackSpeed').getChildByName('Value').getComponent(Label)
        this.lbAttackRange = this.ndSecondAttributes.getChildByName('Label_AttackRange').getChildByName('Value').getComponent(Label)
        this.lbHP = this.ndSecondAttributes.getChildByName('Label_HP').getChildByName('Value').getComponent(Label)
        this.lbWuxingEnhance = this.ndSecondAttributes.getChildByName('Label_WuxingEnhance').getChildByName('Value').getComponent(Label)
        this.lbSkillEnhance = this.ndSecondAttributes.getChildByName('Label_SkillEnhance').getChildByName('Value').getComponent(Label)
        this.lbIgnoreDefense = this.ndSecondAttributes.getChildByName('Label_IgnoreDefense').getChildByName('Value').getComponent(Label)
        this.lbAccuracy = this.ndSecondAttributes.getChildByName('Label_Accuracy').getChildByName('Value').getComponent(Label)
        this.lbCDR =  this.ndSecondAttributes.getChildByName('Label_CDR').getChildByName('Value').getComponent(Label)
        this.lbDodge =  this.ndSecondAttributes.getChildByName('Label_Dodge').getChildByName('Value').getComponent(Label)
        this.lbRage = this.ndSecondAttributes.getChildByName('Label_Rage').getChildByName('Value').getComponent(Label)

        // 装备
        this.ndEquipment = this.node.getChildByName('Equipment')
        this.ndHelmet = this.ndEquipment.getChildByName('Helmet')
        this.ndWeapon = this.ndEquipment.getChildByName('Weapon')
        this.ndArmor = this.ndEquipment.getChildByName('Armor')
        this.ndLeggings = this.ndEquipment.getChildByName('Leggings')
        this.ndShoes = this.ndEquipment.getChildByName('Shoes')
        this.ndPendant = this.ndEquipment.getChildByName('Pendant')
        this.ndBelt = this.ndEquipment.getChildByName('Belt')
        this.ndBracers = this.ndEquipment.getChildByName('Bracers')

        // 武学
        this.ndSkills = this.node.getChildByName('Skills')
        this.ndPassiveSkill1 = this.ndSkills.getChildByName('PassiveSkill1')
        this.ndPassiveSkill2 = this.ndSkills.getChildByName('PassiveSkill2')



        this.initEquipmentNodes();

        console.log("onload playerview", Core.Instance.unlockedPlayers);

        // 确保一些页面不可见
        this.node.getChildByName('SkillDetail').active = false; // 武学详情页面
        //this.node.getChildByName('EquipmentDetail').active = false; // 装备详情页面

        Core.Instance.currentPlayer = Core.Instance.unlockedPlayers[0]
        console.log("Coreinitttaaa Core.Instance.currentPlayer", Core.Instance.currentPlayer);
        //this.loadData(Core.Instance.currentPlayer); // 默认加载第一个玩家



        
    }


    protected onEnable(): void {
        console.log("playerview enable")
        Core.Instance.currentView = EView.PlayerView;

        // 先检查红点
        Core.Instance.unlockedPlayers.forEach((playerType) => {
            //console.log("playerType checkReddot", playerType);  
            this.playerData = Core.Instance.players.get(playerType)
            this.checkReddot(playerType);
        })



        this.playerType = Core.Instance.unlockedPlayers[0] // 默认选中第一个玩家
        //console.log("Core.Instance.unlockedPlayers",Core.Instance.unlockedPlayers)
        this.playerData = Core.Instance.players.get(this.playerType)
        //this.baseAttackSpeed = PlayerConfig[this.playerType].attackSpeed

        this.lightUnlockPlayer();

        //this.playerData.calculateAttributes(true) // 计算属性

           
        Core.Instance.event.on(EEvent.PlayerDataChange, this.onPlayerDataChange, this)                 
        Core.Instance.event.on(EEvent.PlayerDataUpdated, this.onPlayerDataUpdated, this)
        Core.Instance.event.on(EEvent.SkillUpgrade, this.onSkillUpgrade, this)
        Core.Instance.event.on(EEvent.EquipmentChanged, this.onPlayerDataChange, this)
        Core.Instance.event.on(EEvent.PassiveSkillUpdate, this.onPassiveUpdate, this)
        //Core.Instance.event.on(EEvent.PlayerLevelUp, this.loadData, this)
        Core.Instance.event.on(EEvent.PetUpdate, this.onPlayerDataChange, this)



        this.loadData(Core.Instance.currentPlayer);

        
    }

    protected onDisable(): void {
        console.log("onDisable PlayerView");
        //Core.Instance.event.off(EEvent.PlayerSelectedChange, this.onPlayerSelectedChange, this)
        //this.ndBG.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        Core.Instance.event.off(EEvent.PlayerDataChange, this.onPlayerDataChange, this)  
        Core.Instance.event.off(EEvent.PlayerDataUpdated, this.onPlayerDataUpdated, this)
        Core.Instance.event.off(EEvent.SkillUpgrade, this.onSkillUpgrade, this) 
        Core.Instance.event.off(EEvent.EquipmentChanged, this.onPlayerDataChange, this)
        Core.Instance.event.off(EEvent.PassiveSkillUpdate, this.onPassiveUpdate, this)
        Core.Instance.event.off(EEvent.PetUpdate, this.onPlayerDataChange, this)


        Core.Instance.currentView = null;
        Core.Instance.currentSubView = null
    }


    start() {
        // console.log("selected player", Core.Instance.unlockedPlayers[0]); 
        // this.loadData(Core.Instance.currentPlayer);

    }

    update(deltaTime: number) {
        
    }

    private initEquipmentNodes(): void {
        const equipmentTypes = [
            EEquipmentType.Helmet, EEquipmentType.Armor, EEquipmentType.Weapon,
            EEquipmentType.Leggings, EEquipmentType.Shoes, EEquipmentType.Pendant,
            EEquipmentType.Belt, EEquipmentType.Bracers, EEquipmentType.Ring, EEquipmentType.Necklace
        ];
        
        const ndEquipment = this.node.getChildByName('Equipment');
        equipmentTypes.forEach(type => {
            this.equipmentNodes.set(type, ndEquipment.getChildByName(type));
        });
    }


    lightUnlockPlayer(){

        // 让所有解锁的玩家按钮变亮
        for (let i = 0; i < Core.Instance.unlockedPlayers.length; i++) {
            const player = Core.Instance.unlockedPlayers[i];
            const playerNode = this.ndPlayerList.getChildByName(player);
            if (playerNode) {
                playerNode.getComponent(Sprite).color = Color.WHITE; // 变亮
                //playerNode.getComponent(Toggle).interactable = true; // 可交互
            } else {
                console.warn(`Player node ${player} not found in ndPlayerGoBattle`);
            }
            
        }
    }

    /**
     * 检查玩家视图中的红点显示状态
     * @param player 玩家类型
     */
    checkReddot(player:EPlayerType){

        // 初始化各种红点显示状态标志
        let showEquipmentReddot = false  // 装备红点
        let showSkillPointsReddot = false  // 技能点红点
        let showAttributePointsReddot = false  // 属性点红点
        let showSkillPanelReddot = false  // 技能面板红点

        let showReddotOnPLayerList = false;  // 玩家列表红点

        // 检查装备红点
        this.equipmentNodes.forEach((node, type) => {
            const equipment = this.playerData.equipmentData.equipped.get(type);
            if (!equipment) {
                // 如果没有装备，检查背包中是否有该类型的装备
                const hasBetterEquipment = Core.Instance.bag.getEquipmentByType(type).length > 0;
                //console.log("checkReddot PlayerView Core.Instance.bag.getEquipmentByType(type)", Core.Instance.bag.getEquipmentByType(type));
                if (node.getChildByName('Reddot')) {
                    if(hasBetterEquipment){
                        node.getChildByName('Reddot').active = true;
                        showEquipmentReddot = true;
                    }
                    
                }
            } else {
                if (node.getChildByName('Reddot')) {
                    node.getChildByName('Reddot').active = false;
                    
                }
                // // 如果已装备，检查背包中是否有更好的装备
                // if(Core.Instance.bag.getEquipmentByType(type).length <= 0){return}
                // const currentScore = equipment.getScore();
                // const hasBetterEquipment = Core.Instance.bag.getEquipmentByType(type).some(item => item.equipmentType === type && item.getScore() > currentScore);
                // if (node.getChildByName('Reddot')) {
                //     node.getChildByName('Reddot').active = hasBetterEquipment;
                // }
            }
        });

        // 检查武学点红点
        const skillPointsReddot = this.ndSkills.getChildByName("SkillPoint").getChildByName('Reddot');
        if (skillPointsReddot) {
            if(this.playerData.skillPoints > 0){
                skillPointsReddot.active = true;
                showSkillPointsReddot = true;
            }else{
                skillPointsReddot.active = false;
            }

        }
        // 检查潜能点红点
        const attributePointsReddot = this.ndAttributes.getChildByName("AttributePoint").getChildByName('Reddot');
        if (attributePointsReddot) {
            if(this.playerData.attributePoints > 0){
                attributePointsReddot.active = true;
                showAttributePointsReddot = true;
            }else{
                attributePointsReddot.active = false;
            }
        }

        // 检查武学符文红点
        //for (let skill of this.ndSkills) {
        let ndSkillsList = [this.ndSkills.getChildByName('Skill1'),this.ndSkills.getChildByName('Skill2'), this.ndSkills.getChildByName('Skill3')]
        for (let element of ndSkillsList) {
            if(this.playerData.skillData.hasSkillWithoutRune(player+element.name)){
                element.getChildByName('Reddot').active = true;
                showSkillPanelReddot = true;
            }else{
                element.getChildByName('Reddot').active = false;
            }
        }

        // 以上四项检查如果有任意一项为true，则showReddotOnPLayerList为true
        showReddotOnPLayerList = showEquipmentReddot || showSkillPointsReddot || showAttributePointsReddot || showSkillPanelReddot;
        console.log("showReddotOnPLayerList", player, showReddotOnPLayerList, showEquipmentReddot, showSkillPointsReddot, showAttributePointsReddot, showSkillPanelReddot);
        this.ndPlayerList.getChildByName(player).getChildByName('Reddot').active = showReddotOnPLayerList;



    }

    /**
     * 玩家数据变化处理函数
     * 该函数通过playerView间接处理玩家数据变更
     */
    onPlayerDataChange(){  // 从playerView绕一下
        console.log("onPlayerDataChange PlayerView");  // 输出日志，标记函数执行位置
        this.playerData = Core.Instance.players.get(Core.Instance.currentPlayer)  // 获取当前玩家数据
        this.playerData.calculateAttributes(true) // 计算属性，参数true表示强制重新计算
        Core.Instance.save()  // 保存当前游戏状态
    }

    onPlayerDataUpdated() {
        console.log("onPlayerDataUpdated PlayerView");
        // 当玩家数据变化时，重新加载数据
        this.loadData(Core.Instance.currentPlayer);

        //Core.Instance.save()
    }

    // tryLoadPlayer(player: EPlayerType, attempt: number = 0) {
    //     if (this.playerPrefab) {
    //         // 如果预制体已加载，直接调用loadData
    //         this.loadData(player);
    //     } else {
    //         // 如果尝试次数过多（可选），可以停止尝试
    //         if (attempt > 10) { // 例如最多尝试10次
    //             console.error("Failed to load player prefab after multiple attempts");
    //             return;
    //         }
            
    //         // 延迟后重试
    //         setTimeout(() => {
    //             console.log(`Retrying to load player ${player}, attempt ${attempt + 1}`);
    //             this.tryLoadPlayer(player, attempt + 1);
    //         }, 1000); // 每秒重试一次
    //     }
    // }



    onPlayerSelectedChange(){
        console.log("unlockedPlayers", Core.Instance.unlockedPlayers);
        this.loadData(Core.Instance.unlockedPlayers[0])

    }

    loadData(player:EPlayerType){
        //console.log("Playerview load data宠物",player)
        this.playerData = Core.Instance.players.get(player)


        //this.playerData.calculateAttributes(true) // 计算属性
            // 添加这一行：从玩家配置中获取基础攻击速度
        this.baseAttackSpeed = PlayerConfig[player].attackSpeed;

        // 让ndPlayerList的currentPlayer高亮
        this.ndPlayerList.getChildByName(player).getComponent(Sprite).color = new Color(255, 255, 255, 255)
        // 展示player动画
        this.player.removeAllChildren()
        //this.playerPrefab = Core.Instance.prefabMap.get(player);
        this.playerPrefab = ResourceManager.Instance.getRes(PrefabPath[player])
        //console.log("this.playerPrefab", this.playerPrefab);

        

        let node = instantiate(this.playerPrefab);
        node.getChildByName('Rage').active = false
        node.setScale(4, 4)
        this.player.addChild(node)
        node.setPosition(0,0,0)
        node.getComponent(PlayerManager).initState(player)
        node.getComponent(PlayerManager).state = EState.IdleFront

        // 展示基础信息：名字、等级、修为、五行
        this.loadInfomation(player)
        // 展示基础属性和二级属性
        this.loadAttributes()
        // 展示装备
        this.loadEquipment();
        // 检查红点
        this.checkReddot(player);
        // 展示武学
        this.loadSkill(player);


    }

    loadInfomation(player){
        // 展示player的名字、五行
        this.playerName.string = PlayerConfig[player].name
        this.lbWuxing.string = PlayerConfig[player].wuxing
        this.lbWuxing.color = color().fromHEX(PlayerConfig[player].wuxingColor);
        
        // 展示player的等级
        this.ndLevel.getComponent(Label).string ="等级:"+ this.playerData.level
        // 展示player的修为
        this.ndEXP.getComponent(ProgressBar).progress = this.playerData.exp/this.playerData.expToNextLevel
        this.ndEXP.getChildByName('Label').getComponent(Label).string = "修为："+this.playerData.exp + "/" + this.playerData.expToNextLevel

    }

    loadAttributes(){
        
        this.primaryAttribute = Core  .Instance.players.get(Core.Instance.currentPlayer).primaryAttribute // 获取主属性
        // 根据主属性，让对应的属性显示对应颜色，并且粗体
        this.ndAttributes.getChildByName("Label_Strength").getComponent(Label).color = color().fromHEX("#FFFFFF") // 白色
        this.ndAttributes.getChildByName("Label_Strength").getComponent(Label).isBold = false // 非粗体
        this.ndAttributes.getChildByName("Label_Agility").getComponent(Label).color = color().fromHEX("#FFFFFF") // 白色
        this.ndAttributes.getChildByName("Label_Agility").getComponent(Label).isBold = false // 非粗体
        this.ndAttributes.getChildByName("Label_Intelligence").getComponent(Label).color = color().fromHEX("#FFFFFF") // 白色
        this.ndAttributes.getChildByName("Label_Intelligence").getComponent(Label).isBold = false // 非粗体
        this.ndAttributes.getChildByName("Label_InnerPower").getComponent(Label).color = color().fromHEX("#FFFFFF") // 白色
        this.ndAttributes.getChildByName("Label_InnerPower").getComponent(Label).isBold = false // 非粗体
        this.ndAttributes.getChildByName("Label_Vitality").getComponent(Label).color = color().fromHEX("#FFFFFF") // 白色
        this.ndAttributes.getChildByName("Label_Vitality").getComponent(Label).isBold = false // 非粗体
        
        this.ndAttributes.getChildByName("Label_"+this.primaryAttribute).getComponent(Label).color = this.lbWuxing.color // 黄色
        this.ndAttributes.getChildByName("Label_"+this.primaryAttribute).getComponent(Label).isBold = true // 粗体

        // 展示player的属性
        this.lbStrength.string = Util.roundToOne(this.playerData.strength).toString()
        this.lbAgility.string = Util.roundToOne(this.playerData.agility).toString()
        //console.log("宠物this.playerData.agility", this.playerData.agility);
        this.lbIntelligence.string = Util.roundToOne(this.playerData.intelligence).toString()
        this.lbInnerPower.string = Util.roundToOne(this.playerData.innerPower).toString()
        this.lbVitality.string = Util.roundToOne(this.playerData.vitality).toString()

        this.lbAP.string = Util.roundToOne(this.playerData.ap).toString()
        this.lbDP.string = Util.roundToOne(this.playerData.dp).toString()
        this.lbHP.string = Util.roundToOne(this.playerData.hp).toString()
        this.lbCriticalChance.string = Util.roundToOne(this.playerData.criticalChance*100)+"%"
        this.lbCriticalDamage.string = Util.roundToOne(this.playerData.criticalDamage*100) +"%"
        this.lbAttackSpeed.string = Util.roundToOne((this.baseAttackSpeed / this.playerData.attackSpeed) * 100) + "%"
        //console.log("tttttttttttttttthis.baseAttackSpeed", this.baseAttackSpeed);  
        //console.log("ttttttttttttttttthis.playerData.attackSpeed", this.playerData.attackSpeed);

        this.lbAttackRange.string = Util.roundToOne(this.playerData.attackRange).toString()
        this.lbWuxingEnhance.string = Util.roundToOne(this.playerData.wuxingEnhance*100) + "%"
        this.lbSkillEnhance.string = Util.roundToOne(this.playerData.skillEnhance*100) + "%"
        this.lbIgnoreDefense.string = Util.roundToOne(this.playerData.ignoreDefense*100) + "%"
        this.lbCDR.string = Util.roundToOne(this.playerData.CDR*100) + "%"
        this.lbDodge.string  = Util.roundToOne(this.playerData.dodge*100) + "%"
        this.lbAccuracy.string = Util.roundToOne(this.playerData.accuracy*100) + "%"
        this.lbRage.string = Util.roundToOne(this.playerData.rageRegen).toString()

        // 展示player的属性点
        this.ndAttributes.getChildByName('AttributePoint').getChildByName('Value').getComponent(Label).string = this.playerData.attributePoints.toString()

    }

    loadSkill(player){
        

        let ndSkillsList = [this.ndSkills.getChildByName('Skill1'),this.ndSkills.getChildByName('Skill2'), this.ndSkills.getChildByName('Skill3')]
        // 展示player武学
        // 检查武学mask
        let currentSkill = Core.Instance.currentSkill  // 记录一下，因为skillNode enable会触发修改Core.Instance.currentSkill
        for (let i = 0; i < ndSkillsList.length; i++) {

            const skillNode = ndSkillsList[i];
            skillNode.active = false;
            skillNode.active = true; // 先显示出来
            
        }
        Core.Instance.currentSkill = currentSkill // 再还原


        // load ndSkills 下面的skill的icon和文字信息
        for (let i = 1; i < ndSkillsList.length+1; i++) {
            const element = ndSkillsList[i-1];
            const skillType = player+'Skill'+i
            element.getChildByName('Title').getComponent(Label).string = SkillConfig[player+'Skill'+i].name
            //console.log("SkillConfig[player+'Skill'+i].name", SkillConfig[player+'Skill'+i].name);
            element.getChildByName('Desc').getComponent(Label).string = SkillConfig[player+'Skill'+i].desc
            console.log("player+'Skill'+i+'Icon'", player+'Skill'+i+'Icon');
            ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[player+'Skill'+i+'Icon'])
            .then((spriteFrame) => {
                element.getChildByName('Icon').getComponent(Sprite).spriteFrame = spriteFrame;
            })
            .catch((error) => {
                console.error("加载武学图标失败:", error);
            });
            // ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[player+'Skill'+i+'Icon']+"/spriteFrame").then((spriteFrame) => {
            //     element.getChildByName('Icon').getComponent(Sprite).spriteFrame = spriteFrame;
            // }).catch((error) => {
            //     console.error("加载武学图标失败:", error);
            // });
            element.getChildByName('Level').getChildByName("Value").getComponent(Label).string = this.playerData.skillData.skills.get(skillType as ESkill).level.toString()


        }


        // 展示武学点
        console.log("this.playerData.skillPoints", this.playerData.skillPoints);
        this.ndSkills.getChildByName('SkillPoint').getChildByName("Value").getComponent(Label).string = this.playerData.skillPoints.toString()


        // let ndPassiveSkillsList = [this.ndSkills.getChildByName('PassiveSkill1'),this.ndSkills.getChildByName('PassiveSkill2'), this.ndSkills.getChildByName('PassiveSkill3')]
        // for (let i = 0; i < ndPassiveSkillsList.length; i++) {
        //     const skillNode = ndPassiveSkillsList[i];

        // 展示心法（被动武学）
        let passiveSkills = this.playerData.skillData.passiveSkills;
        let assignedPassiveSkill = this.playerData.skillData.assignedPassiveSkill;
        console.log(" playertype passiveSkills",  Core.Instance.currentPlayer, passiveSkills,assignedPassiveSkill);
        // 遍历this.playerData.skillData.passiveSkills，将武学显示在ndPassiveSkill上
        if(this.playerData.level >= 5){
            if(assignedPassiveSkill){
                //console.log(">5")
                //this.ndPassiveSkill1.getChildByName('Icon').getComponent(Sprite).spriteFrame = ResourceManager.Instance.getRes<SpriteFrame>(PicPath[passiveSkills[0]+'Icon'])
                ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[assignedPassiveSkill+'Icon']+"/spriteFrame")
                .then((spriteFrame) => {
                    this.ndPassiveSkill1.getChildByName('Icon').getComponent(Sprite).spriteFrame = spriteFrame;
                })
                .catch((error) => {
                    console.error("加载被动武学图标失败:", error);
                });
            }

        }else{
            this.ndPassiveSkill1.getChildByName('Icon').getComponent(Sprite).spriteFrame = null
        }
    }

private loadEquipment(): void {
    console.log("updateEquipment in playerView");
    console.log("updateEquipment in playerView this.playerData.equipmentData.equipped", this.playerData.equipmentData.equipped);
    
    // 遍历所有装备槽位
    this.equipmentNodes.forEach((equipmentNode, equipmentType) => {
            equipmentNode.getComponent(BagItem).init(this.playerData.equipmentData.equipped.get(equipmentType));

    });
}


onResouceChange() {
    
}

    onBtnAttributeUpgrade(event: Event, attribute: EBaseAttribute) {
        console.log("点击了属性升级按钮", attribute);
        console.log("888888888 playerType in playerView onBtn", this.playerData.playerType);
        // 检查属性点是否足够
        if (this.playerData.attributePoints <= 0) {
            console.error("属性点不足，无法升级属性");
            Core.Instance.showTips("潜能点不足，无法升级属性")
            return;
        }

        // 升级属性
        this.playerData.upgradeAttribute(attribute);
        //console.log("升级后的属性数据:", this.playerData);

        // 更新面板显示
        //this.loadData(Core.Instance.currentPlayer);

        //Core.Instance.event.emit(EEvent.PlayerDataUpdated); // 通知其他组件更新武学点显示
    }

    onBtnCheckUnlockedPlayers(event: Event) {
        console.log("onBtnCheckUnlockedPlayers");

// 检查等级
    }

    onSkillUpgrade(value: ESkill, skill: any) {

        this.loadData(Core.Instance.currentPlayer); // TODO: 这里可以优化，只更新武学相关的部分，而不是全部重新加载

        //Core.Instance.save()
    }

    onBtnLevelUpForTest() {
        console.log("onBtnLevelUpForTest");
        // 测试升级
        for ( let i = 0; i < 30; i++) {
            this.playerData.levelUp();
        
        }

        this.loadData(Core.Instance.currentPlayer); // 更新面板显示
        Core.Instance.event.emit(EEvent.PlayerDataUpdated); // 通知其他组件更新武学点显示
    }

    onBtnStageUpForTest() {
        console.log("onBtnLevelUpForTest");
        
        // 遍历所有游戏模式，将每个模式的最大关隘数+1
        for (const mode in Core.Instance.modeMaxStage) {
            if (Core.Instance.modeMaxStage.hasOwnProperty(mode)) {
                Core.Instance.modeMaxStage[mode as EGameMode] += 1;
            }
        }

        Core.Instance.save();
        
        console.log("Updated modeMaxStage:", Core.Instance.modeMaxStage);
    }

    onBtnAddMoneyForTest() {
        console.log("onBtnAddMoneyForTest");
        // 测试增加金钱
        Core.Instance.gold += 10000;
        Core.Instance.event.emit(EEvent.ResourceChanged); // 通知其他组件更新金钱显示
        Core.Instance.save();
    
    }


    onButtonEquipmentSwitch() {
        console.log("onButtonEquipmentSwitch");
        // 切换装备界面
        this.ndEquipmentSwitchView.active = !this.ndEquipmentSwitchView.active; // 切换显示状态
        //Core.Instance.event.emit(EEvent.SwitchView, Context.ArsenalView);
        //Core.Instance.event.emit(EEvent.SwitchView, Context.PlayerView);
    }



    onPassiveUpdate(value){
        console.log("onPassiveUpdate value:", value)

        ResourceManager.Instance.loadRes<SpriteFrame>(PicPath[value+"Icon"]+"/spriteFrame").then((spriteFrame) => {
            this.ndPassiveSkill1.getChildByName("Icon").getComponent(Sprite).spriteFrame = spriteFrame;
        }).catch((error) => {
            console.error("加载装备图标失败:", error);
        });


        Core.Instance.players.get(Core.Instance.currentPlayer).skillData.assignedPassiveSkill = value as EPassiveSkill;

        this.onPlayerDataChange();  // 通知数据变化，保存游戏等操作

        //console.log("onPassiveUpdate321ItemBox onButtonChooseThis assignedPassiveSkill:", Core.Instance.players.get(Core.Instance.currentPlayer).skillData.assignedPassiveSkill);




    }
}


